package com.markhsiu.MiniMQ.broker.store;

import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.markhsiu.MiniMQ.model.Message;

public class StoreManager {
 

	/**
     * 消息存储
     * map :
     *    String :topic主题
     *    Queue<Message> : 消息队列
     */
    private static final Map<String,Queue<Message>> messageStore = new ConcurrentHashMap<>();
    
    //-----------  消息存储管理
    public static  void addMessage(Message e){
    	Queue<Message> topciQueue = messageStore.get(e.getTopic());
    	if(topciQueue == null){
    		topciQueue = new ConcurrentLinkedQueue<Message>();
    		messageStore.put(e.getTopic(), topciQueue);
    	}
    	topciQueue.add(e);
    	System.out.println("topic : " + e.getTopic() + " == "+ topciQueue.size());
    }
    
    public static Message pollMessage(String topic){
    	Queue<Message> topicQueue = messageStore.get(topic);
    	if(topicQueue != null){
    		Message first = topicQueue.poll();
    		//移除空主题队列
    		if(topicQueue == null || topicQueue.size() == 0){
    			messageStore.remove(topic);
    		}
    		return first;
    	}
    	return null;
    }
    
  
    /**
     * 默认存储方式为内存
     * @return
     */
    public static <T>  BaseStore<T> defaultStore(){
    	return new MemoryStore<>();
    } 
}
